package logic

import (
	"context"
	"encoding/json"
	"goods_srv/global"
	"goods_srv/goods_proto"
	"goods_srv/model"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 获取所有的分类
func (g *GoodsServer) GetAllCategoryList(ctx context.Context, in *goods_proto.Empty) (*goods_proto.CategoryListResponse, error) {
	var category []model.Category
	//查询分类表中等级一下的所有内容(子查询为等级一下的等级二,等级二下的等级三)
	global.DB.Model(&model.Category{}).Where(&model.Category{Level: 1}).Preload("SubCategory.SubCategory").Find(&category)
	//序列化数据
	categoryJson, _ := json.Marshal(category)
	return &goods_proto.CategoryListResponse{JsonData: string(categoryJson)}, nil

}

// 新增分类信息
func (g *GoodsServer) CreateCategory(ctx context.Context, in *goods_proto.CategoryInfoRequest) (*goods_proto.CategoryInfoResponse, error) {
	category := model.Category{}
	//赋值
	category.Name = in.Name
	category.Level = in.Level
	//如果等级不是1,就将父ID赋值
	if in.Level != 1 {
		category.ParentCategoryID = in.ParentCategory
	}

	category.IsTab = in.IsTab
	//不存在就创建
	tx := global.DB.Save(&category)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "新增分类失败")
	}

	return &goods_proto.CategoryInfoResponse{Id: category.ID}, nil
}

// 删除商品分类
func (g *GoodsServer) DeleteCategory(ctx context.Context, in *goods_proto.DeleteCategoryRequest) (*goods_proto.Empty, error) {
	if result := global.DB.Delete(&model.Category{}, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品分类不存在")
	}
	return &goods_proto.Empty{}, nil
}

// 修改商品分类
func (g *GoodsServer) UpdateCategory(ctx context.Context, in *goods_proto.CategoryInfoRequest) (*goods_proto.Empty, error) {
	var category model.Category
	if result := global.DB.First(&category, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品分类不存在")
	}
	if in.Name != "" {
		category.Name = in.Name
	}
	if in.Level != 0 {
		category.Level = in.Level
	}
	if in.ParentCategory != 0 {
		category.ParentCategoryID = in.ParentCategory
	}
	if in.IsTab {
		category.IsTab = in.IsTab
	}
	tx := global.DB.Updates(&category)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改商品分类失败")
	}
	return &goods_proto.Empty{}, nil
}
